package server.configuration;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class ServerConfigurationManager
{
	private final JAXBContext context;
	private final String configFileLocation;
	
	public ServerConfigurationManager(String configFileLocation) throws InstantiationException
	{
		this.configFileLocation = configFileLocation;
		
		try
		{
			context = JAXBContext.newInstance(ServerConfiguration.class);
		}
		catch (JAXBException e)
		{
			throw new InstantiationException();
		}
	}
	public void saveConfiguration(ServerConfiguration config)
	{
		Marshaller marshaller;
		File configFile = new File(configFileLocation);
		
		try
		{
			marshaller = context.createMarshaller();
			marshaller.setProperty("jaxb.formatted.output", true);
			marshaller.marshal(config, configFile);
		}
		catch (JAXBException e)
		{
			e.printStackTrace();
		}
	}
	public ServerConfiguration loadConfiguration()
	{
		Unmarshaller unmarshaller;
		ServerConfiguration config = null;
		
		try
		{
			unmarshaller = context.createUnmarshaller();
			config = (ServerConfiguration) unmarshaller.unmarshal(new File(configFileLocation));
		}
		catch (JAXBException e)
		{
			e.printStackTrace();
		}
		
		return config;
	}
}
